package cn.rjzjh.tapestry.busi.service.security;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.access.vote.AbstractAccessDecisionManager;
import org.springframework.security.access.vote.AffirmativeBased;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

//AffirmativeBased  
public class AccessDecisionManager extends AbstractAccessDecisionManager{

	// In this method, need to compare authentication with configAttributes.
	// 1, A object is a URL, a filter was find permission configuration by this
	// URL, and pass to here.
	// 2, Check authentication has attribute in permission configuration
	// (configAttributes)
	// 3, If not match corresponding authentication, throw a
	// AccessDeniedException.
	

	public boolean supports(ConfigAttribute attribute) {
		return true;
	}

	public boolean supports(Class<?> clazz) {
		return true;
	}

	@Override
	public void decide(Authentication authentication, Object object,
			Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {

		// 如果是开发者拥有所有权限
		Object principal = authentication.getPrincipal();// 得到授权用户
		if (principal instanceof UserInfo) {
			UserInfo user = (UserInfo) principal;
			if (user.isDev()) {
				return;
			}
		}

		// 如果资源需要的角色与用户角色匹配就可以通过
		for (ConfigAttribute resRole : configAttributes) {
			for (GrantedAuthority userRole : authentication.getAuthorities()) {
				if (((SecurityConfig) resRole).getAttribute().equals(
						userRole.getAuthority())) {
					return;
				}
			}
		}
		throw new AccessDeniedException("没有权限");
	}
}
